package api

import (
	"context"
	"coolcar/forms"
	"coolcar/global"
	authpb "coolcar/proto/auth_out/v1"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	accountID, _ := c.Get("accountID")

	loginForm := forms.LoginForm{}
	err := c.ShouldBind(&loginForm)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "参数错误",
		})
	}

	res, err := global.AuthHandler.Login(context.Background(), &authpb.LoginRequest{
		Account:  loginForm.Account,
		Password: loginForm.Password,
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "调用AuthClient服务失败",
		})
	}

	// 生成token
	token, err := global.JWTTokenGen.GenerateToken(res.UserId)
	if err != nil {
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"msg": "生成token失败",
			})
		}
		return
	}
	//fmt.Println("tkn", token)

	c.JSON(http.StatusOK, gin.H{
		"AccessToken": token,
		"AccountID":   accountID,
		"ExpiresIn":   global.JWTTokenGen.Expired.Seconds(),
	})
}
